03. More Powerful GET Requests

Routes & GET Requests Example Prep

More Powerful GET Requests

Hello world is all well and good, but suppose we wanted to make a GET request for some more useful data. GET requests can return all kinds of data, for example, imagine we wanted a JavaScript object to hold user data for us.

  • At the top of the demo code we just looked at, we could create an empty JavaScript object with the code const appData = {}. The variable appData now acts as the endpoint for all our app data. Later we will learn how to POST data to the app endpoint, but first let's add the line of code that will return our JavaScript object when the GET request is made.

Routes & GET Requests Example

var express = require('express')
var app = express()
// Create JS object
const appData = {}
// Respond with JS object when a GET request is made to the homepage
app.get('/all', function (req, res) {
  res.send(appData)
})

Routes & GET Requests Example Summary

In this example, we created a new route named '/all', so that the route 'localhost:3000/all' will now trigger the GET request, which will return the JavaScript object as laid out in the server code above.

  • Notice, the callback function of the GET request takes two parameters, arbitrarily named req and res in this example. Every GET request produces a request, which is the data provided by the GET request, and a response, which is the data returned to the GET request. Below, you can see the long list of information that comes with each GET request:

Routes & GET Requests Graphic

A portion of the data returned by the `req` (request) parameter of a GET route.

A portion of the data returned by the req (request) parameter of a GET route.

Routes & GET Requests Quiz

QUESTION:

Add a GET route to an app instance, using the path ‘/data’, and a function with the parameters req and res, and returns the string ‘welcome!’

SOLUTION:

NOTE: The solutions are expressed in RegEx pattern. Udacity uses these patterns to check the given answer

Routes & GET Requests Quiz 1 Solution

Routes & GET Requests Quiz 2

QUESTION:

Reflect

The arguments for GET and POST route callback functions are often interchangeably named (req, res) and (request, response). Which one of these makes more sense to use? What if you had to write them twenty or fifty times in a coding session? You can name these arguments for GET and POST requests anything you like, but it should be meaningful and effective.

ANSWER:

Thanks for your response.

Routes & GET Requests Further Research

More on Express routing and GET requests

In this lesson we learned how Express methods can be used to define routes and handle GET requests made to a server created with Node and Express.
For more on Express routing methods and GET requests you can visit the 'Routing' guide in the Express documentation.